<script lang="ts" setup>
import { getListByConditions, resetMenusByRoleId, urls } from '@/index';
import { navyMenu } from '@/utils/navyMenu';
import type { Menu, Role } from '@/index.d';
import { useRequest } from 'vue-request';

const currentRole = defineModel<Role>('currentRole', { required: true });
const currentMenu = defineModel<Menu>('currentMenu', { required: true });

const navyMenuShow = computed(() => {
  return navyMenu.filter(subMenu => {
    if (!subMenu.isShow || subMenu.children === undefined || subMenu.children.length < 1) {
      return false;
    } else {
      subMenu.children = subMenu.children.filter(item => item.isShow);
      return subMenu.children.length > 0;
    }
  });
});

const {
  data: menuListByRoleIdWithoutPage,
  runAsync: getMenuListByRoleIdWithoutPageAsync,
  loading
} = useRequest(() => getListByConditions<Menu>(urls.menu, { roleId: currentRole.value.id }));

const defaultCheckedKeys = computed(() =>
  menuListByRoleIdWithoutPage.value?.map(item => item.title)
);

const excludeSubMenu = (keys: string[]): string[] => {
  navyMenu.forEach(item => {
    if (item.children && item.children.length > 0) {
      if (keys.includes(item.title)) {
        keys = keys.filter(key => key != item.title);
      }
    }
  });
  return keys;
};

const handleCheck = async (data: Menu, { checkedKeys }: { checkedKeys: string[] }) => {
  await resetMenusByRoleId({
    roleId: currentRole.value.id as number,
    roleName: currentRole.value.name as string,
    currentMenuTitle: data.title,
    menus: excludeSubMenu(checkedKeys)
  });
  await getMenuListByRoleIdWithoutPageAsync();
  currentMenu.value.title = data.title;
  currentMenu.value.isShow = defaultCheckedKeys.value?.includes(data.title);
};

const handleNodeClick = (data: Menu) => {
  currentMenu.value.title = data.title;
  currentMenu.value.isShow = defaultCheckedKeys.value?.includes(data.title);
  currentMenu.value.fullPath = data.fullPath;
  currentMenu.value.name = data.name;
};

watch(
  () => defaultCheckedKeys.value,
  value => {
    currentMenu.value.isShow = value?.includes(currentMenu.value.title);
  }
);
</script>
<template>
  <el-scrollbar :max-height="1000">
    <el-tree
      :loading="loading"
      :data="navyMenuShow"
      node-key="title"
      :current-node-key="currentMenu.title"
      show-checkbox
      :default-checked-keys="defaultCheckedKeys"
      highlight-current
      default-expand-all
      @check="handleCheck"
      @node-click="handleNodeClick"
      :check-on-click-leaf="false"
    >
      <template #default="{ data }">{{ data.title }}</template>
    </el-tree>
  </el-scrollbar>
</template>
<style lang="scss" scoped></style>
